package init

import (
	"heartbeat/controller"
	"heartbeat/database"
	"heartbeat/utils"
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/huyinghuan/mail"
)

func SendEmail(title string, content string) error {

}
func rightPad2Len(s string, padStr string, overallLen int) string {
	var padCountInt int
	padCountInt = 1 + ((overallLen - len(padStr)) / len(padStr))
	var retStr = s + strings.Repeat(padStr, padCountInt)
	return retStr[:overallLen]
}

var LastSendEmailTime int64

func AlarmByEmail() {
	config := utils.GetConfig()
	Alarm := config.Alarm
	interval := Alarm.Email
	if interval < 1 {
		interval = 5
	}
	//邮件发送间隔
	if time.Now().Unix()-LastSendEmailTime < 60*interval {
		log.Println("邮件发送间隔保护启用...")
		return
	}
	LastSendEmailTime = time.Now().Unix()
	badList, err := controller.GetTimeoutVPS()
	if err != nil {
		return
	}
	if len(badList) < Alarm.Numbers {
		return
	}
	title := "报警！VPS故障总数:" + strconv.Itoa(len(badList))
	temp := make(map[string][]*controller.StoreValue)
	for _, item := range badList {
		host := strings.Split(item.IP, ":")[0]
		if _, ok := temp[host]; ok {
			temp[host] = append(temp[host], item)
		} else {
			temp[host] = []*controller.StoreValue{item}
		}
	}
	sum := []string{}
	detail := []string{}

	for key, value := range temp {
		sum = append(sum, rightPad2Len(key, " ", 30)+" 故障数: "+strconv.Itoa(len(value)))
		for _, item := range value {
			detail = append(detail, rightPad2Len(item.IP, " ", 30)+" "+time.Unix(item.Time, 0).Format("2006-01-02 15:04:05"))
		}
	}
	content := strings.Join(sum, "\r\n")
	content += "\r\n==============详细列表==============\r\n"
	content += strings.Join(detail, "\r\n")

	Email := config.Email
	redis := database.GetRedisClient()
	contact, _ := redis.Get("alarm:contact").Result()
	contactArr := strings.Split(contact, ",")
	sender := &mail.MailSender{
		Username: Email.Username,
		Password: Email.Password,
		Port:     Email.Port,
		Host:     Email.Host}
	if err := sender.SendMail(title, content, contactArr); err != nil {
		log.Fatal(err)
		log.Fatalln("邮件发送失败")
	}
}
